<template>
  <view class="edit-group">
    <!-- 导航栏 -->
    <u-navbar 
      title="编辑群聊" 
      :is-back="true" 
      @back="navigateBack"
    ></u-navbar>
    
    <!-- 表单内容 -->
    <view class="form-content">
      <view class="form-item">
        <text class="label">群名称</text>
        <input 
          type="text" 
          placeholder="请输入群名称" 
          v-model="groupName"
        />
      </view>
      
      <view class="form-item">
        <text class="label">群头像</text>
        <view class="avatar-container" @click="selectAvatar">
          <image :src="avatarUrl" mode="aspectFill"></image>
          <text class="upload-text">上传头像</text>
        </view>
      </view>
      
      <view class="form-item">
        <text class="label">群描述</text>
        <textarea 
          placeholder="请输入群描述" 
          v-model="description"
        ></textarea>
      </view>
    </view>
    
    <!-- 创建按钮 -->
    <u-button 
      class="submit-btn" 
      type="primary" 
      @click="updateGroup"
      :disabled="!isValidForm"
    >
      保存更改
    </u-button>
  </view>
</template>

<script>
import { GroupApi, CommonApi } from '@/api/index.js';
import websocketMixin from '@/utils/mixins/websocketMixin'

export default {
  mixins: [websocketMixin],
  data() {
    return {
      groupId: null,
      groupName: "",
      avatarUrl: "",
      description: ""
    };
  },
  computed: {
    isValidForm() {
      return this.groupName.trim() !== "";
    }
  },
  onLoad(options) {
    this.groupId = options.groupId;

    if (!this.groupId) {
      uni.showToast({
        title: '群组ID缺失',
        icon: 'none'
      });
      uni.navigateBack();
      return;
    }

    this.getGroupInfo();
  },
  methods: {
    navigateBack() {
      uni.navigateBack();
    },
    async getGroupInfo() {
      try {
        const res = await GroupApi.getGroupInfoById(this.groupId);

        if (res.code === 200) {
          const group = res.data;
          this.$set(this, 'groupName', group.name);
          this.avatarUrl = group.avatarUrl;
          this.description = group.description;
        } else {
          uni.showToast({ title: '加载失败', icon: 'none' });
        }
      } catch (e) {
        console.error("获取群信息失败", e);
        uni.showToast({ title: '网络错误', icon: 'none' });
      }
    },
    async selectAvatar() {
      try {
        const res = await new Promise((resolve, reject) => {
          uni.chooseImage({
            count: 1,
            success: resolve,
            fail: reject
          });
        });

        const tempFilePath = res.tempFilePaths[0];

        uni.showLoading({ title: '上传中...' });

        const uploadRes = await CommonApi.uploadFile(tempFilePath);

        uni.hideLoading();

        if (uploadRes && uploadRes.code === 200) {
          uni.showToast({ title: '上传成功', icon: 'success' });
          this.avatarUrl = uploadRes.data.url;
        } else {
          uni.showToast({ title: '上传失败', icon: 'none' });
        }

      } catch (e) {
        uni.hideLoading();
        console.error("上传错误", e);
        uni.showToast({ title: '上传失败', icon: 'none' });
      }
    },
    async updateGroup() {
      if (!this.isValidForm) {
        uni.showToast({ title: '请输入群名称', icon: 'none' });
        return;
      }

      const group = {
        id: this.groupId,
        name: this.groupName,
        avatarUrl: this.avatarUrl || '',
        description: this.description || ''
      };

      uni.showLoading({ title: '提交中...' });

      try {
        const res = await GroupApi.updateGroup(group);

        if (res && res.code === 200) {
          uni.hideLoading();
          uni.showToast({
            title: '更新成功',
            icon: 'success',
            duration: 1500,
            success: () => {
              setTimeout(() => {
                uni.navigateBack(); // 返回上一页
              }, 800);
            }
          });
        } else {
          uni.hideLoading();
          uni.showToast({ title: res.msg || '更新失败', icon: 'none' });
        }
      } catch (e) {
        uni.hideLoading();
        console.error("更新群组出错", e);
        uni.showToast({ title: '网络异常，请重试', icon: 'none' });
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.edit-group {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.form-content {
  padding: 30rpx;
  background-color: white;
  margin-top: 20rpx;
}

.form-item {
  margin-bottom: 40rpx;

  .label {
    display: block;
    font-size: 28rpx;
    color: #666;
    margin-bottom: 15rpx;
  }

  input {
    width: 100%;
    height: 80rpx;
    padding: 0 20rpx;
    background-color: #f5f5f5;
    border-radius: 10rpx;
    font-size: 28rpx;
  }
  
  textarea {
    width: 100%;
    padding: 20rpx;
    border-radius: 12rpx;
    border: 2rpx solid #eee;
    font-size: 28rpx;
    box-sizing: border-box;
  }

  textarea {
    height: 160rpx;
  }
}

.avatar-container {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  border: 2rpx dashed #ccc;
  padding: 40rpx 0;
  border-radius: 16rpx;
  background-color: #fafafa;

  image {
    width: 120rpx;
    height: 120rpx;
    border-radius: 60rpx;
    margin-bottom: 20rpx;
  }

  .upload-text {
    color: #999;
    font-size: 24rpx;
  }
}

.submit-btn {
  margin: 60rpx 30rpx;
}
</style>